//
//  HomeViewController.m
//  PlantGoWorker
//
//  Created by 纪翀 on 17/4/23.
//  Copyright © 2017年 m-training. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeFuncTableViewCell.h"
#import "MyTaskStocksViewController.h"
#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"
#import "MyWebViewController.h"
#import "MyInfoViewController.h"
#import "TimeOffViewController.h"
#import "MyOTViewController.h"
#import "MyFeedbackViewController.h"
#import "CheckStorkViewController.h"
#import "RepairListViewController.h"
#import "HomeQRViewController.h"
#import "ResourceDetailViewController.h"

#define HOME_ICONS  \
  @{@"1":@"我的任务.png",\
    @"2":@"我要加班.png",\
    @"3":@"我要反馈.png",\
    @"4":@"扫码盘点.png",\
    @"5":@"我要请假.png",\
    @"6":@"复壮报损.png",\
    @"7":@"复壮报损.png"\
    }

#define AD_WIDTH    ([UIScreen mainScreen].bounds.size.width)
#define AD_HEIGHT   (AD_WIDTH*120/320)

#define PAGER_WIDTH   (AD_WIDTH /2)
#define PAGER_HEIGHT  (5)
#define PAGER_BOTTOM  10
#define PAGER_START_X  (AD_WIDTH - PAGER_WIDTH)/2
@interface HomeViewController ()
{
    UIView       * _advertView;
    UIScrollView * _advertScrolView;
    UIPageControl * _adPageControl;
    NSArray *_modules;
    NSArray *_adverts;
    NSDictionary *_myInfo;
}
@end

@implementation HomeViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    _modules = [_pageData objectForKey:@"modules"];
    _adverts = [_pageData objectForKey:@"adverts"];
    [self loadMyInfo];
    [self initFuncTabView];
    NSTimer   *timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}


- (UIView *) headerView{
    //广告栏
    _advertView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, AD_WIDTH, AD_HEIGHT)];
    _advertScrolView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, AD_WIDTH, AD_HEIGHT)];

    [_advertScrolView setBackgroundColor:[UIColor lightGrayColor]];
    _advertScrolView.pagingEnabled = YES;
    _advertScrolView.tag = 100;
    _advertScrolView.delegate = self;
    _advertScrolView.contentSize = CGSizeMake(AD_WIDTH * _adverts.count, _advertScrolView.bounds.size.width*120/320);
    for (int i = 0; i < _adverts.count; i ++) {
        
        NSString *urlStr =[[_adverts objectAtIndex:i] objectForKey:@"picUrl"];

        UIButton  *button = [UIButton buttonWithType:UIButtonTypeCustom];
        
        button.frame = CGRectMake(AD_WIDTH*i, 0, AD_WIDTH, AD_HEIGHT);
        button.tag = i;
        [button addTarget:self action:@selector(advertClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [button sd_setBackgroundImageWithURL:[NSURL URLWithString:urlStr] forState:UIControlStateNormal placeholderImage:nil];
        [button.imageView setContentMode:UIViewContentModeScaleAspectFill];
        //        button.imageView.contentMode = UIViewContentModeScaleToFill;
        //        button.contentMode = UIViewContentModeScaleToFill;
        [_advertScrolView addSubview:button];
    }
    
    
    _adPageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(PAGER_START_X, AD_HEIGHT-PAGER_BOTTOM, PAGER_WIDTH, PAGER_HEIGHT)];
    _adPageControl.numberOfPages = _adverts.count;
    
    [_advertView addSubview:_advertScrolView];
    [_advertView addSubview:_adPageControl];
    
    return _advertView;

}
- (IBAction)myInfoBtnClick:(id)sender {
    if (_myInfo == nil){
        [self loadMyInfo];
    }
    MyInfoViewController *vc = [[MyInfoViewController alloc]init];
    vc.myInfoDic = _myInfo;
    [self.navigationController pushViewController:vc animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


#pragma mark - UITabView
- (void)initFuncTabView
{
    _tabView.rowHeight = 70;
    _tabView.tableHeaderView = [self headerView];
    _tabView.bounces = NO;
    [_tabView registerNib:[UINib nibWithNibName:@"HomeFuncTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_modules count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *module = [_modules objectAtIndex:indexPath.row];
    NSString *name = [module objectForKey:@"name"];
    int moduleNo = [[module objectForKey:@"moduleNo"] intValue];
    HomeFuncTableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    [cell.titleLabel setText:name];
    cell.tag = moduleNo;
    //图标
    NSString *moduleNoStr = [NSString stringWithFormat:@"%d", moduleNo];
    [cell.imgView setImage:[UIImage imageNamed:[HOME_ICONS objectForKey:moduleNoStr]]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *module = [_modules objectAtIndex:indexPath.row];
    int moduleNo = [[module objectForKey:@"moduleNo"] intValue];
    NSString *token = [GlobalVar getVarName:@"token"];
    
    switch (moduleNo) {
        // 我的任务
        case 1:{
            MyTaskStocksViewController *vc = [[MyTaskStocksViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        // 我要加班
        case 2:
        {
            MyOTViewController *vc = [[MyOTViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        //我要反馈
        case 3:{
            MyFeedbackViewController *vc = [[MyFeedbackViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        //扫码盘点
        case 4:{
            CheckStorkViewController *vc = [[CheckStorkViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        // 我要请假
        case 5:
        {
            TimeOffViewController *vc = [[TimeOffViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        // 复壮
        case 6:{
            RepairListViewController *vc = [[RepairListViewController alloc]init];
            vc.type = @"0";
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        // 报损
        case 7:{
            RepairListViewController *vc = [[RepairListViewController alloc]init];
            vc.type = @"1";
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
            break;
    }
}

#pragma mark - ScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.tag == 100) {
        _adPageControl.currentPage = scrollView.contentOffset.x/AD_WIDTH;
    }
}



- (void)advertClick:(UIButton *)btn
{
    NSLog(@"upInside...");
    
    NSDictionary* advDic = [_adverts objectAtIndex:btn.tag];
    
    MyWebViewController *vc = [[MyWebViewController alloc] init];
    [vc.titleLabel setText:@"信息"];
    vc.url = [advDic objectForKey:@"lindUrl"];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)loadMyInfo{
    
    _avatarImgBtn.layer.masksToBounds = YES;
    _avatarImgBtn.layer.cornerRadius = 18;
    
    NSString *token = [GlobalVar getVarName:@"token"];

    [SendRequestClass commonRequest:@"/api/myinfo"
                            postDic:@{@"token":token}
                    completionBlock:^(NSDictionary *myInfoDic)  {
                        if ([[myInfoDic objectForKey:@"code"] intValue] == SUCC_RESP){
                            NSLog(@"Success MyInfo");
                            _myInfo = [myInfoDic objectForKey:@"data"];
                            [_avatarImgBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:[_myInfo objectForKey:@"picUrl"]]  forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"avatar_placeholder.png"]];
                            [_avatarImgBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:[_myInfo objectForKey:@"picUrl"]] forState:UIControlStateFocused placeholderImage:[UIImage imageNamed:@"avatar_placeholder.png"]];
                        }
                        else{
                            NSLog(@"Fail MyInfo");
                            [MyHint showHint:[myInfoDic objectForKey:@"message"]];
                        }
                        
                        
                    }failureBlock:^(NSDictionary *dic){
                        NSLog(@"Network error");
                        [MyHint showHint:@"网络出现故障"];
                    }
     ];

}


- (void)onTimer
{
    static  int i;
    
    
    if (i >= 0) {
        i ++;
        
        
    }
    if (i >= [_adverts count]) {
        
        i=0;
    }
    
    _advertScrolView.contentOffset = CGPointMake([UIScreen mainScreen].bounds.size.width*i,0);
    
}

- (IBAction)QRBtnClick:(UIButton *)sender {
    HomeQRViewController *vc = [[HomeQRViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
@end
